package com.hippo.javacore.multithreading;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @ClassName ThreadDemo13
 * @Description TODO 等待唤醒机制
 * @Author tangxl
 * @create 2023-03-14 15:41
 **/
public class ThreadDemo13 {

    // 定义一个锁对象
    static Lock lock = new ReentrantLock();

    //定义一个生产者--厨师类
    public static class Cook extends Thread {
        @Override
        public void run() {
            while (true) {
                // 同步代码块
                synchronized (ThreadDemo13.lock) {
                    System.out.println("厨师正在做饭");
                    try {
                        // 做饭需要3秒
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    System.out.println("厨师做好了饭");
                    // 唤醒等待的线程
                    ThreadDemo13.lock.notify();
                    try {
                        // 做完饭后，进入等待状态
                        System.out.println("厨师休息");
                        ThreadDemo13.lock.wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }
    }

    //定义一个消费者--吃货类
    public static class Eater extends Thread {

        @Override
        public void run() {
            while (true) {
                // 同步代码块
                synchronized (ThreadDemo13.lock) {
                    System.out.println("吃货正在吃饭");
                    try {
                        // 吃饭需要3秒
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    System.out.println("吃货吃完了饭");
                    // 唤醒等待的线程
                    ThreadDemo13.lock.notify();
                    try {
                        // 吃完饭后，进入等待状态
                        System.out.println("吃货先等着");
                        ThreadDemo13.lock.wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }
    }

    public static void main(String[] args) {
        /**
         * 实现生产者与消费者（等待唤醒机制），实现线程轮流交替执行的效果
         */
        // 创建线程
        Thread t1 = new Cook();
        Thread t2 = new Eater();

        // 线程命名
        t1.setName("厨师");
        t2.setName("吃货");

        // 线程执行
        t1.start();
        t2.start();
    }
}
